import { login, getInfo, getDetailInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 用户信息
    userInfo: null
  }
}

const state = getDefaultState()

const mutations = {
  updateUserInfo(state, info) {
    state.userInfo = info
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 实现一个action用来登录
  async login ({ commit }, form) {
    try {
      const ret = await login({
        mobile: form.username,
        password: form.password
      })
      if (ret.code === 10000) {
      // 登陆成功,先缓存到state,在保存到本地
        commit('SET_TOKEN', ret.data)
        setToken(ret.data)
        return Promise.resolve(true)
      } else {
      // 登陆失败
        return Promise.resolve(false)
      }
    } catch {
      return Promise.resolve(false)
    }
  },

  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 获取用户信息
  async getInfo({ commit }) {
    const daseInfo = await getInfo()
    const detailInfo = await getDetailInfo(daseInfo.data.userId)
    if (daseInfo.code === 10000) {
      // 触发mutation更新用户信息
      commit('updateUserInfo', {
        // 合并用户信息
        ...daseInfo.data,
        ...detailInfo.data
      })
    }
  },

  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 退出
  logout({ commit }) {
    // 1 删除token
    commit('SET_TOKEN', '')
    // 2 删除用户信息
    commit('updateUserInfo', null)
    // 3 删除缓存中的token
    removeToken()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
